package com.xj.service;

import com.xj.model.Ticket;
import com.xj.model.User;
import com.xj.model.exceptions.LoginRegisterException;
import com.xj.utils.BrowerHolderUtils;
import com.xj.utils.MD5Utils;
import com.xj.utils.TicketUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 复杂的登陆逻辑service
 */
@Service
public class LoginService {

  @Autowired
  private UserService userService;

  @Autowired
  private TicketService ticketService;

    /**
     * 注册一个用户，并返回用户t票
     * @return 用户当前的t票
     */
    public String register(User user) throws Exception {
        //信息检查
        if (userService.getUser(user.getEmail()) != null) {
            throw new LoginRegisterException("用户邮箱已经存在！");
        }
        //密码加密
        String plain = user.getPassword();
        String md5 = MD5Utils.encrypt(plain);
        user.setPassword(md5);
        //数据库添加用户
        userService.addUser(user);

        //生成用户t票
        Ticket ticket = TicketUtils.createTicketByUid(user.getId());
        //数据库添加t票
        ticketService.addTicket(ticket);

        BrowerHolderUtils.setHostUser(user);
        return ticket.getTicket();
    }

  /**
   * 登录逻辑，先检查邮箱和密码，然后更新t票。
   * @return 返回最新t票
   * @throws Exception 账号密码错误
   */
  public String login(String email, String password) throws Exception {
    User user = userService.getUser(email);

    //登录信息检查
    if (user == null) {
      throw new LoginRegisterException("邮箱不存在");
    }
    if(!StringUtils.equals(MD5Utils.encrypt(password),user.getPassword())) {
      throw new LoginRegisterException("密码不正确");
    }

    //检查ticket
    Ticket t = ticketService.getTicket(user.getId());
    //如果没有t票。解决退出登陆后没有t票的用户。同时必然没有过期
    if(t == null){
      t = TicketUtils.createTicketByUid(user.getId());
      ticketService.addTicket(t);
      BrowerHolderUtils.setHostUser(user);
      return t.getTicket();
    }


    //是否过期
    if(t.getExpiredAt().before(new Date())){
      //删除
      ticketService.deleteTicket(t.getId());
      t = TicketUtils.createTicketByUid(user.getId());
      ticketService.addTicket(t);
    }

    //当前线程只保留最新的用户t票
    BrowerHolderUtils.setHostUser(user);
    return t.getTicket();
  }

  /**
   * 用户退出登录，只需要删除数据库中用户的t票
   * @param t
   */
  public void logout(String t){
    ticketService.deleteTicket(t);
  }
}
